package com.yimils.core.goods.serivce.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yimils.core.goods.dto.BrandAddReq;
import com.yimils.core.goods.dto.BrandUpdateReq;
import com.yimils.core.goods.entity.BrandEntity;
import com.yimils.core.goods.mapper.BrandMapper;
import com.yimils.core.goods.serivce.BrandService;
import com.yimils.core.goods.vo.BrandRes;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandMapper, BrandEntity> implements BrandService {
    @Override
    public Boolean saveBrand(BrandAddReq brandAddReq) {
        BrandEntity brandEntity = new BrandEntity();
        brandEntity.setBrandName(brandAddReq.getBrandName());
        brandEntity.setSupplierId(brandAddReq.getSupplierId());
        brandEntity.setState(Boolean.FALSE);
        brandEntity.setCreateTime(LocalDateTime.now());
        brandEntity.setUpdateTime(LocalDateTime.now());
        return save(brandEntity);
    }

    @Override
    public Boolean updateBrand(BrandUpdateReq brandUpdateReq) {
        QueryWrapper<BrandEntity> qw = new QueryWrapper<>();
        qw.lambda().eq(BrandEntity::getId, brandUpdateReq.getBrandId()).eq(BrandEntity::getState, Boolean.FALSE);
        BrandEntity one = getOne(qw);
        one.setBrandName(brandUpdateReq.getBrandName());
        one.setUpdateTime(LocalDateTime.now());

        return saveOrUpdate(one);

    }

    @Override
    public Boolean deleteBrand(List<Long> brandIds) {

        QueryWrapper<BrandEntity> qw = new QueryWrapper<>();
        qw.lambda().in(BrandEntity::getId, brandIds).eq(BrandEntity::getState, Boolean.FALSE);

        List<BrandEntity> brandEntities = list(qw);
        if (CollectionUtils.isEmpty(brandEntities)) {
            return Boolean.FALSE;
        }
        brandEntities.forEach(o -> {
            o.setState(Boolean.TRUE);
            o.setUpdateTime(LocalDateTime.now());
        });
        return saveOrUpdateBatch(brandEntities);
    }

    @Override
    public List<BrandRes> listBrand(Long supplierId) {
        QueryWrapper<BrandEntity> qw = new QueryWrapper<>();
        qw.lambda().eq(BrandEntity::getSupplierId, supplierId).eq(BrandEntity::getState, Boolean.FALSE);
//todo   平台和个人没有区分
        List<BrandEntity> brandEntities = list(qw);
        if (CollectionUtils.isEmpty(brandEntities)) {
            return Collections.emptyList();
        }
        return brandEntities.stream().map(o -> {
            BrandRes brandRes = new BrandRes();
            brandRes.setBrandName(o.getBrandName());
            brandRes.setBrandId(o.getId());
            return brandRes;
        }).collect(Collectors.toList());
    }
}
